import os
import uuid
from datetime import datetime
from fileinput import filename

from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import and_, desc
from app.models.music import MusicTemplate, MusicFile
from app.models.user import User
from app.extensions import db
from app.services.aliyun_oss import aliyun_oss, AliyunOSS
from app.utils.decorators import handle_errors

music_bp = Blueprint('music', __name__, url_prefix='/api/music')



@music_bp.route('/templates', methods=['GET'])
@jwt_required()
@handle_errors
def get_music_templates():
    """获取音乐模板列表"""
    current_user_id = get_jwt_identity()
    
    # 查询参数
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('pageSize', 20, type=int)
    template_type = request.args.get('template_type', '')
    
    # 构建查询
    query = MusicTemplate.query.filter_by(user_id=current_user_id)
    
    # 根据模板类型筛选
    if template_type:
        query = query.filter_by(template_type=template_type)
    
    # 分页查询
    query = query.order_by(desc(MusicTemplate.created_at))
    total = query.count()
    templates = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return jsonify({
        'templates': [template.to_dict() for template in templates],
        'total': total,
        'page': page,
        'pageSize': page_size,
        'pages': (total + page_size - 1) // page_size
    })


@music_bp.route('/templates', methods=['POST'])
@jwt_required()
@handle_errors
def create_music_template():
    """创建音乐模板"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    template = MusicTemplate(
        user_id=current_user_id,
        template_name=data['template_name'],
        template_type=data.get('template_type', 'hospital'),
        category=data['category'],
        playlist_name=data['playlist_name'],
        play_mode=data.get('play_mode', 'sequence'),
        remark=data.get('remark', ''),
        is_default=data.get('is_default', False)
    )
    
    # 如果设置为默认模板，取消其他默认模板
    if template.is_default:
        MusicTemplate.query.filter_by(
            user_id=current_user_id,
            is_default=True
        ).update({'is_default': False})
    
    db.session.add(template)
    db.session.commit()
    
    return jsonify({
        'message': '音乐模板创建成功',
        'template': template.to_dict()
    }), 201


@music_bp.route('/templates/<int:template_id>', methods=['PUT'])
@jwt_required()
@handle_errors
def update_music_template(template_id):
    """更新音乐模板"""
    current_user_id = get_jwt_identity()
    
    template = MusicTemplate.query.filter_by(
        id=template_id,
        user_id=current_user_id
    ).first()
    
    if not template:
        return jsonify({'error': '音乐模板不存在'}), 404
    
    data = request.get_json()
    
    # 更新允许的字段
    if 'template_name' in data:
        template.template_name = data['template_name']
    if 'template_type' in data:
        template.template_type = data['template_type']
    if 'category' in data:
        template.category = data['category']
    if 'playlist_name' in data:
        template.playlist_name = data['playlist_name']
    if 'play_mode' in data:
        template.play_mode = data['play_mode']
    if 'remark' in data:
        template.remark = data['remark']
    if 'is_default' in data:
        template.is_default = data['is_default']
        # 如果设置为默认模板，取消其他默认模板
        if template.is_default:
            MusicTemplate.query.filter_by(
                user_id=current_user_id,
                is_default=True
            ).update({'is_default': False})
    
    db.session.commit()
    
    return jsonify({
        'message': '音乐模板更新成功',
        'template': template.to_dict()
    })


@music_bp.route('/templates/<int:template_id>', methods=['DELETE'])
@jwt_required()
@handle_errors
def delete_music_template(template_id):
    """删除音乐模板"""
    current_user_id = get_jwt_identity()
    
    template = MusicTemplate.query.filter_by(
        id=template_id,
        user_id=current_user_id
    ).first()
    
    if not template:
        return jsonify({'error': '音乐模板不存在'}), 404
    
    db.session.delete(template)
    db.session.commit()
    
    return jsonify({'message': '音乐模板删除成功'})


@music_bp.route('/upload', methods=['POST'])
@jwt_required()
@handle_errors
def upload_music():
    """上传音乐文件到OSS"""
    current_user_id = get_jwt_identity()
    
    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({'error': '没有上传文件'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '文件名不能为空'}), 400
    
    # 获取分类和播放列表信息
    category = request.form.get('category', '')
    playlist_name = request.form.get('playlist_name', '')
    
    try:
        # 读取文件内容
        file_data = file.read()
        
        # 重置文件指针，确保后续操作可以正常进行
        file.seek(0)
        
        # 上传到OSS
        res = aliyun_oss.upload_file(file_data)
        
        # 保存文件信息到数据库
        music_file = MusicFile(
            filename=file.filename,
            oss_key=res['object_name'],
            oss_url=res['url'],
            file_size=len(file_data),
            category=category,
            playlist_name=playlist_name
        )
        
        db.session.add(music_file)
        db.session.commit()
        
        return jsonify({
            'message': '音乐文件上传成功',
            'file': music_file.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'上传失败: {str(e)}'}), 500


@music_bp.route('/files', methods=['GET'])
@jwt_required()
@handle_errors
def get_music_files():
    """获取音乐文件列表"""
    current_user_id = get_jwt_identity()
    
    # 查询参数
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('pageSize', 20, type=int)
    category = request.args.get('category', '')
    
    # 构建查询
    query = MusicFile.query
    
    # 根据分类筛选
    if category:
        query = query.filter_by(category=category)
    
    # 分页查询
    query = query.order_by(desc(MusicFile.created_at))
    total = query.count()
    files = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return jsonify({
        'files': [file.to_dict() for file in files],
        'total': total,
        'page': page,
        'pageSize': page_size,
        'pages': (total + page_size - 1) // page_size
    })


@music_bp.route('/files/<int:file_id>', methods=['DELETE'])
@jwt_required()
@handle_errors
def delete_music_file(file_id):
    """删除音乐文件"""
    current_user_id = get_jwt_identity()
    
    # 查找音乐文件
    music_file = MusicFile.query.filter_by(id=file_id).first()
    
    if not music_file:
        return jsonify({'error': '音乐文件不存在'}), 404
    
    try:

        # 从数据库删除记录
        db.session.delete(music_file)
        db.session.commit()
        
        return jsonify({'message': '音乐文件删除成功'})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除失败: {str(e)}'}), 500